package com.lagou.ipersistence.type;

import com.lagou.ipersistence.io.Resources;

import javax.xml.soap.Text;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * @author Yan Jiahong
 * Created on 2020/11/15
 */
public class TypeAliasRegistry {
    private final Map<String, Class<?>> TYPE_ALIASES = new HashMap<>();

    public TypeAliasRegistry() {
        registerAlias("string", String.class);
    }

    public void registerAlias(String alias, Class<?> value) {
        if (alias == null) {
            throw new TypeException("别名参数不能为空");
        }
        String key = alias.toLowerCase(Locale.ENGLISH);
        Class<?> existedVal = TYPE_ALIASES.get(key);
        if (TYPE_ALIASES.containsKey(key) && existedVal != null && existedVal.equals(value)) {
            throw new TypeException("别名'" + alias + "'已经映射到值'" + existedVal + "'了");
        } else {
            TYPE_ALIASES.put(key, value);
        }
    }

    public Map<String, Class<?>> getTypeAliases() {
        return Collections.unmodifiableMap(TYPE_ALIASES);
    }

    public <T> Class<T> resolveClass(String string) {
        try {
            if (string == null) {
                return null;
            }
            String key = string.toLowerCase(Locale.ENGLISH);
            Class<T> value;
            if (TYPE_ALIASES.containsKey(key)) {
                value = (Class<T>) TYPE_ALIASES.get(key);
            } else {
                return Resources.classForName(string);
            }
            return value;
        } catch (ClassNotFoundException e) {
            throw new TypeException("无法解析类型别名'" + string + "', 原因: " + e, e);
        }
    }
}
